var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var price = 0;
var hot = 0;
var app = getApp();

var screen_w = 320;

var wxAuthFail = true;
var inviteuid = 0;
var uid = '0';
var linkcode = '';
var topicid = "";
var dataall;
var loadingMore = false;
var allGoodsData = {};
var page = 1;
var hasMore = true;
var messagetmp = '';

Page({
  data: {
    util: util,

    logo_url: '',

    page: 1,
    limit: 20,
    uid: '',
    token: '',

    data: [],
    noData: false,
    imgDomain: app.globalData.imgDomain,
    goodTypeName: '',
    goodTypeId: 0,
    pinSign: 0,

    postuid: '',
    hasMore: true,
    hasLoadding: false,
    priceorder: 0,
    hotorder: 0,
    hidecata: true,
    allcata: [],
    nowcata: [],
    nowArtistList:[],
    hideArtist: true,
    selectArtist: '',
    screen_h:480,
    content_item_w: 100,
    goodTypeView_w: 100,
    colorSet: '',


    goodsList: [],
    currcata: 0,
    isIphone_x: false,
    catadata: [],
    guigeData: [],
    selectGuige: '',
    countValue: 1,
    gwc_count: 0,
    waithao: 0,

    gcataid: "",
    username: '',


    attribute: '', //商品属性集合
    showAttribute: false, //控制商品有属性事显示

    showPrefood: false,
    showMainfood: false,
    showDrink: false,
    showSubDrink: false,

    drinksArray: [],
    prefoodArray: [],
    mainfoodArray: [],


    tabcurrcata: 0,
    commentcurrcata: 0,
    hide_commentview: true,
    ghsIndex: 0,

    topNum: 0, //返回顶部

    leftScrollHeight:480,
    selScrollHeight:480

    // ------------------

  },
  onLoad: function(options) {

    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
    });


    var titlename = '收藏品';

    wx.setNavigationBarTitle({
      title: titlename,
    });

    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });
    wx.getSystemInfo({
      success: function(res) {

        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
          screen_w: res.windowWidth,
          content_w: res.windowWidth - 83,
          goodTypeView_w: res.windowWidth - 83,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          leftScrollHeight: isIphone_x ? (res.windowHeight - 70) : (res.windowHeight - 50),
          selScrollHeight: isIphone_x ? (res.windowHeight - 100) : (res.windowHeight - 80)
        });

      }
    })
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('goodslist/goodslist', function(data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });
    //获取颜色配置
    app.getColorSetData(function(color) {
      var col = color.goods_col ? parseInt(color.goods_col) : 3;
      col = col > 0 ? col : 3;
      that.setData({
        colorSet: color,
        content_item_w: (that.data.content_w - (col + 1) * 5) / col,
      })
      that.resetNavColor();
    });

    this.setData({
      logo_url: options.logo_url ? options.logo_url : '',
      goodTypeId: options.cataid ? options.cataid : '',
      postuid: options.uid ? options.uid : '',
      pinSign: options.pin ? options.pin : 0
    });


    //读取登录用户信息
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          userinfo: res,
          token: res.token
        });
      }
    }, '');

    allGoodsData = {};

    var inviteuid = options.inviteuid;

    util.api({
      data: {
        //"tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "goodstype"
      },
      success: function(responseData) {
        console.log("goodstype", responseData.data);
        var goodsType = responseData.data;
        if (!goodsType.msg) {
          for (var i = 0; i < goodsType.length; i++) {
            goodsType[i].page = 1;
          }
          dataall = goodsType;
          
            that.setData({
              catadata: dataall,
              selectCata: dataall[0],
              gcataid: dataall[0].goods_id,
              nowcata: dataall[0].child ? dataall[0].child : '',
            });
          
          let page = that.data.selectCata.page;
          that.loadGoodsListData(page);
          //去读取绑定了这个一级分类id的艺术家列表
          that.loadArtistBindGoodtype(dataall[0].goods_id, 0);
        } else {
          wx.hideLoading();
        }

      },
    });

  },

  loadArtistBindGoodtype: function (cataid, dataallIndex){
    // http://admin.jawanology.com/api.php?ac=getUserByCataid&binduid=21484&cataid=732&publickey=ZGZvI1mi8Q
    // 加上了这个接口，ac = getUserByCataid，binduid - 商户uid，cataid - 一级分类id
    var that = this;
    util.api({
      data: {
        //"tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "getUserByCataid",
        "cataid": cataid
      },
      success: function (responseData) {
        console.log("绑定了一级分类的艺术家：", responseData.data);
        if (!responseData.data.msg){
          dataall[dataallIndex].artistList = responseData.data;
          that.setData({
            nowArtistList: responseData.data
          })
        } else {
          that.setData({
            nowArtistList: ''
          })
        }
      },
    });
  },

  loadMore: function() {
    if (!loadingMore && hasMore) {
      let selCata = this.data.selectCata;
      let page = selCata.page + 1;
      selCata.page = page;
      this.loadGoodsListData(page);
    }
  },

  loadGoodsListData: function(cpage) {
    var that = this;
    wx.showLoading({
      title: that.data.tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    })

    var goodsTypeId = that.data.selectCata.goods_id;
    var artistId = that.data.selectArtist ? that.data.selectArtist.uid : '';
    loadingMore = true;

    var zhiding = that.data.selectCata.zhiding ? that.data.selectCata.zhiding : '';
    var num = that.data.selectCata.num ? that.data.selectCata.num : '10';
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      //tc: that.data.tc,
      orgid: util.orgid,
      postuid: artistId,
      zhiding: zhiding,
      ordernum: 1,//按排序字段排序 0和不传是不安这个排，1是升序，2是降序
      page: cpage,
      gtype: goodsTypeId,
      pin: that.data.pinSign,
      sellprice: price,
      hot: hot,
      num: num
    };

    console.log("商店商品请求参数：", params);
    util.api({
      data: params,
      success: function(responseData) {
        console.log("商店商品数据:", responseData);
        var resData = responseData.data;
        var newData = '';
        if (resData.msg) {
          hasMore = false;
          if (cpage <= 1) {
            that.setData({
              goodsList: [],
            });
          };
        } else {
          if (cpage > 1) {
            newData = that.data.goodsList.concat(resData);
          } else {
            newData = resData;
          };
          
          that.setData({
            goodsList: newData,
          });

          if (!that.data.selectArtist && goodsTypeId.length <= 3){
            allGoodsData[goodsTypeId] = newData;
            console.log("allGoodsData:", allGoodsData);
          } else {
            console.log("不缓存数据！！！！！！！！！1");
          }
        }
        loadingMore = false;
        if (cpage <= 1 && that.data.goodsList.length <= 0) {
          that.setData({
            noData: true
          });
        };

        wx.hideLoading();
      }
    });
  },


  priceOrder: function() {
    hot = 0;
    page = 1;
    if (price == 0 || price == 1) {
      price = 2;
    } else {
      price = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      // goodTypeName: '',
      hidecata: true,
      hideArtist: true
    });
    this.loadGoodsListData(1);
  },
  hotOrder: function() {
    price = 0;
    page = 1;
    if (hot == 0 || hot == 1) {
      hot = 2;
    } else {
      hot = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      // goodTypeName: '',
      hidecata: true,
      hideArtist: true
    });
    this.loadGoodsListData(1);
  },



  goAtherPage: function(e) {

    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  //点击左侧菜单切换
  changeCata: function(event) {

    if (loadingMore) {
      return false;
    }

    price = 0;
    hot = 0;
    var that = this;
    var cataid = event.currentTarget.dataset.cataid;
    var cataindex = event.currentTarget.dataset.index;
    console.log(cataid, cataindex);
    page = 1;
    hasMore = true;
    loadingMore = false;
    that.setData({
      // infodata: dataall[cataindex]['child'] ? dataall[cataindex]['child'] : [],
      selectCata: dataall[cataindex],
      selectArtist: '',
      gcataid: dataall[cataindex].goods_id.substring(0, 3),
      currcata: cataindex,
      currView: cataindex,
      nowcata: dataall[cataindex].child ? dataall[cataindex].child : '',
      searchVal: '',
      hidecata: true,
      hideArtist: true,
      priceorder: 0,
      hotorder: 0,
      goodTypeName: '',
      noData: false
    });
    if (!dataall[cataindex].artistList || dataall[cataindex].artistList.length <= 0) {
      //如果没有艺术家数据，则去读取
      that.loadArtistBindGoodtype(cataid, cataindex);
    } else {
      //
      that.setData({
        nowArtistList: dataall[cataindex].artistList
      })
    }
    console.log("gcataid:changeCata|||||||||||||" + that.data.gcataid);
    var goodsTypeId = that.data.selectCata.goods_id;
    var data = allGoodsData[goodsTypeId];
    console.log("goodsType = " + goodsTypeId + "; data = " + data);
    if (data && data.length > 0) {
      that.setData({
        goodsList: data,
      });
    } else {
      that.loadGoodsListData(1);
    }

  },


  showType: function (event) {
    var that = this;
    this.setData({
      hidecata: false,
      hideArtist:true
    })
  },
  hideType: function (event) {
    var that = this;
    this.setData({
      hidecata: true
    })
  },

  showArtist: function (event) {
    var that = this;
    this.setData({
      hidecata: true,
      hideArtist: false
    })
  },
  hideArtistView: function (event) {
    var that = this;
    this.setData({
      hideArtist: true
    })
  },

  selectGoodsType: function (e) {
    var goodsType = e.currentTarget.dataset.type;
    goodsType.page = 1;
    this.setData({
      selectCata: goodsType,
      selectArtist: '',
      goodTypeName: goodsType.cname,
      hidecata: true,
      noData: false
    });
    hot = 0;
    price = 0;
    hasMore = true;
    this.loadGoodsListData(1);
  },

  selectArtistAction: function (e) {
    var artist = e.currentTarget.dataset.type;
    this.setData({
      selectArtist: artist,
      hideArtist: true,
      noData: false
    });
    hot = 0;
    price = 0;
    hasMore = true;
    this.loadGoodsListData(1);
  },

  //跳转
  goAtherPageReList: function(e) {
    var url = e.currentTarget.dataset.link;

    wx.navigateTo({
      url: url
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function(e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  getLoginInfo: function() {
    var that = this;
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {
        console.log("daying" + res.uid);
        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })


        var canEdit = false;
        if (that.data.data && that.data.data.user && res.uid == that.data.data.user.uid) {
          canEdit = true;
        }
        //设置用户信息
        app.GetUserInfo(res.uid, function(u_res) {
          console.log("getUserInfo:", u_res);
          //更新数据
          that.setData({
            canEdit: canEdit ? canEdit : u_res.isgroup == 1
          })
        });
      } else {
        wxAuthFail = true;
      }
    }, inviteuid)
  },



  //保存formId
  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({
        url: path
      })
    }
  },




  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    var that = this;
    var gwc_datas = wx.getStorageSync('gwc_datas');

    this.setData({
      gwc_count: gwc_datas.length
    });

  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },

  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  }


})